//
//  ShareView.m
//  haiyibao
//
//  Created by 曹雪莹 on 2016/11/26.
//  Copyright © 2016年 韩元旭. All rights reserved.
//

#import "ShareView.h"
#import "ImageWithLabel.h"
#import "AppDelegate.h"

#define ScreenWidth			[[UIScreen mainScreen] bounds].size.width
#define ScreenHeight		[[UIScreen mainScreen] bounds].size.height
#define SHAREVIEW_BGCOLOR   [UIColor colorWithRed:1.00f green:1.00f blue:1.00f alpha:1]
#define WINDOW_COLOR        [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4]
#define ANIMATE_DURATION    0.25f
#define LINE_HEIGHT         74
#define NORMAL_SPACE        7
#define LABEL_HEIGHT		0
#define COLUMN_COUNT        4

@interface ShareView ()

//	所有标题
@property (nonatomic, strong) NSArray  *shareBtnTitleArray;
//	所有图片
@property (nonatomic, strong) NSArray  *shareBtnImageArray;
//	整个底部分享面板的 backgroundView
@property (nonatomic, strong) UIView   *bgView;
//	分享面板取消按钮上部的 View
@property (nonatomic, strong) UIView   *topSheetView;
//	所有的分享按钮
@property (nonatomic, copy) NSMutableArray *buttons;

@property (nonatomic, copy) void(^fontHandle)();

@end

@implementation ShareView

- (instancetype)initWithShareHeadOprationWith:(NSArray *)titleArray andImageArry:(NSArray *)imageArray fontHandle:(void (^)(void))fontHandle {
	
	self = [super init];
	if (self) {
        //添加夜间模式和字号
        BOOL isNight = [[NSUserDefaults standardUserDefaults] boolForKey:kNightMode];
        NSString *lightImageName = @"pop_night";
        if (isNight) {
            lightImageName = @"pop_light";
        }
        
        
        NSMutableArray *titleArr = [NSMutableArray arrayWithArray:titleArray];
        [titleArr addObject:@"夜间"],[titleArr addObject:@"字号"];
        NSMutableArray *imageArr = [NSMutableArray arrayWithArray:imageArray];
        [imageArr addObject:lightImageName],[imageArr addObject:@"pop_font"];
        
		_shareBtnTitleArray = titleArr;
		_shareBtnImageArray = imageArr;
        
        self.fontHandle = fontHandle;

		self.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
		//	背景，带灰度
		self.backgroundColor = WINDOW_COLOR;
		//	可点击
		self.userInteractionEnabled = YES;
		//	点击背景，收起底部分享面板，移除本视图
		UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedCancel)];
		[self addGestureRecognizer:tapGesture];
		
		//	加载分享面板
		[self loadUIConfig];
	}
	return self;
}

/**
 加载自定义视图，按钮的tag依次为（200 + i）
 */
- (void)loadUIConfig {
	
	[self addSubview:self.bgView];
	[self.bgView addSubview:self.topSheetView];
    
	//	按钮
	for (NSInteger i = 0; i < self.shareBtnTitleArray.count; i++) {
		
		CGFloat x = self.bgView.bounds.size.width / COLUMN_COUNT * ( i % COLUMN_COUNT);
		CGFloat y = LABEL_HEIGHT + (i / COLUMN_COUNT) * LINE_HEIGHT;
		CGFloat w = self.bgView.bounds.size.width / COLUMN_COUNT;
		CGFloat h = 70;
		
		CGRect frame =  CGRectMake(x, y, w, h);
		ImageWithLabel *item = [ImageWithLabel imageLabelWithFrame:frame Image:[UIImage imageNamed:self.shareBtnImageArray[i]] LabelText:self.shareBtnTitleArray[i]];
		item.labelOffsetY = 6;
		
		item.tag = 200 + i;
		UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(itemClick:)];
		[item addGestureRecognizer:tapGes];
		[self.topSheetView addSubview:item];
		
		[self.buttons addObject:item];
	}
	//	弹出
	[UIView animateWithDuration:ANIMATE_DURATION animations:^{
		self.bgView.frame = CGRectMake(0, ScreenHeight - CGRectGetHeight(self.bgView.frame), ScreenWidth, CGRectGetHeight(self.bgView.frame));
	}];
	
}

#pragma mark --------------------------- Selector

/**
 点击取消
 */
- (void)tappedCancel {
	
	[UIView animateWithDuration:ANIMATE_DURATION animations:^{
		[self.bgView setFrame:CGRectMake(0, ScreenHeight, ScreenWidth, 0)];
		self.alpha = 0;
	} completion:^(BOOL finished) {
		if (finished) {
			[self removeFromSuperview];
		}
	}];
}

/**
 按钮点击

 @param tapGes 手势
 */
- (void)itemClick:(UITapGestureRecognizer *)tapGes {
	
    NSInteger index = tapGes.view.tag - 200;
    if (index != self.buttons.count - 2) {
        [self tappedCancel];
    }

    if (index < [_shareBtnTitleArray count] - 2) {
        if (self.btnClick) {
            self.btnClick(index);
        }
    } else {
        if (index == [_shareBtnTitleArray count] - 2) {
            //夜间模式
            BOOL isNight = [[NSUserDefaults standardUserDefaults] boolForKey:kNightMode];
            [[NSUserDefaults standardUserDefaults] setBool:!isNight forKey:kNightMode];
            if (!isNight) {
                [AppDelegate sharedAppDelegate].maskWindow.alpha = 0.7;
                ImageWithLabel *iwl = [self.buttons objectAtIndex:self.buttons.count - 2];
                iwl.imageView.image = [UIImage imageNamed:@"pop_light"];
            } else {
                [AppDelegate sharedAppDelegate].maskWindow.alpha = 0;
                ImageWithLabel *iwl = [self.buttons objectAtIndex:self.buttons.count - 2];
                iwl.imageView.image = [UIImage imageNamed:@"pop_night"];
            }

        } else {
            if (self.fontHandle) {
                self.fontHandle();
            }
        }
        
    }
}

#pragma mark --------------------------- getter

- (UIView *)bgView {
	
	if (_bgView == nil) {
		
		_bgView = [[UIView alloc] init];
        _bgView.backgroundColor = [UIColor whiteColor];
		
		//	根据图标个数，计算行数，计算 backgroundView 的高度
		NSInteger index;
		if (_shareBtnTitleArray.count % COLUMN_COUNT == 0) {
			
			index = _shareBtnTitleArray.count / COLUMN_COUNT;
		} else {
			
			index = _shareBtnTitleArray.count / COLUMN_COUNT + 1;
		}
		_bgView.frame = CGRectMake(0, ScreenHeight, ScreenWidth, LINE_HEIGHT * index);
	}
	return _bgView;
}

- (UIView *)topSheetView {
	
	if (_topSheetView == nil) {
		
		_topSheetView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(_bgView.frame), CGRectGetHeight(_bgView.frame))];
		_topSheetView.backgroundColor = [UIColor whiteColor];
		_topSheetView.alpha = 0.8;
	}
	return _topSheetView;
}

- (NSArray *)buttons {
	
	if (!_buttons) {
		_buttons = [NSMutableArray arrayWithCapacity:5];
	}
	return _buttons;
}

#pragma mark --------------------------- User-Defined
- (void)setOtherBtnColor:(UIColor *)otherBtnColor {
	
	for (id res in _bgView.subviews) {
		
		if ([res isKindOfClass:[UIButton class]]) {
			
			UIButton *button = (UIButton *)res;
			[button setTitleColor:otherBtnColor forState:UIControlStateNormal];
		}
	}
}

- (void)setOtherBtnFont:(NSInteger)otherBtnFont {
	
	for (id res in _bgView.subviews) {
		
		if ([res isKindOfClass:[UIButton class]]) {
			
			UIButton *button = (UIButton *)res;
			button.titleLabel.font = [UIFont systemFontOfSize:otherBtnFont];
		}
	}
}

- (void)setDuration:(CGFloat)duration {
	
	self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:duration];
}

@end
